<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>搜索用户</template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 搜索区域开始 -->
        <van-search
            v-model="keyword"
            shape="round"
            background="#27BA9B"
            placeholder="用户名/手机号"
            class="search-wrap"
            show-action
        >
            <template #action>
                <div @click="handleSearch" style="color: #fff;">搜索</div>
            </template>
        </van-search>
        <!-- 搜索区域结束 -->

        <!-- 搜索列表区域开始 -->
        <div class="list-wrap">
            <template v-for="(item, index) in userList" :key="index">
                <TridentCellItem :item="item" v-if="item?.name" @click="$router.push(item.url || '')"/>
            </template>
        </div>
        <!-- 搜索列表区域结束 -->

    </div>
</template>

<script lang="ts" setup>
import { reqUserListAPI } from '@/apis/user';
import type { CellItem } from '@/types/global'
import type { SearchUserParams } from '@/types/user'
import { inject, reactive, ref } from 'vue'

// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global:any = inject('global')

const keyword = ref<string>('')
// ----------------- 定义全局变量结束 -----------------



// ------------------- 搜索功能开始 -------------------
// 搜索参数
const params = reactive<SearchUserParams>({
    mobile: '',
    username: ''
})

// 用户列表
const userList = ref<CellItem[]>([])

// 搜索用户
const searchUser = async () => {
    params.mobile = ''
    params.username = ''
    if (keyword.value) {
        userList.value = []
        // 判断搜索关键字是手机号还是用户名
        const pattern = /^1[3|5|7|8|9]\d{9}$/
        if (pattern.test(keyword.value)) {
            params.mobile = keyword.value
        } else {
            params.username = keyword.value
        }

        const result = await reqUserListAPI(params)
        result.data.users.forEach((user) => {
            userList.value.push({
                name: user.username,
                image_url: global.MINIO_FILE_DOMAIN + user.avatar_url,
                url: '/waitAdd?uid='+user.uid
            })
        })
    }
}

// 处理搜索
const handleSearch = () => {
    searchUser()
}
// ------------------- 搜索功能结束 -------------------
</script>

<style scoped lang="scss">
page,
.container {
    height: 100vh;
    .search-wrap {
        padding-top: 55px;
    }

    .list-wrap {

    }
}
</style>